const GET = 'GET';
const POST = 'POST';
const DELETE = 'DELETE';


const baseURL = "https://j53421893f.zicp.fun";//配置的域名。
var tokenKey = "token";
var exceptionAddrArr = [ '/login','/list'];
/* 请求头处理函数 */
function CreateHeader(url){
let header = {'content-type': 'application/json'}
/* 如果url传入的不是'/login',则返回-1，意思就是除登录外的其他请求都需要加token*/
if (exceptionAddrArr.indexOf(url) == -1) {  //排除请求时不需要token的地址
  let token ='Bearer '+wx.getStorageSync(tokenKey);
  // header.Authorization = token;
  header['Authorization'] = token;
}
return header;
}
function request(method,url,data){
  /* 请求头 */
  let header = CreateHeader(url);
  //console.log("header",header);
   /*  'content-type':'application/json',
  'Authorization':'Bearer '+wx.getStorageSync('token') */
  return new Promise((resolve,reject) => {
    wx.request({
      url: baseURL + url,
      method:method,
      // data:method === method ? JSON.stringify(data) : data,
      data: data,
      header:header,
      success(res){
        //请求成功
        //判断code是否为0表示成功
        if(res.data.code === 200){
          resolve(res);
          //更新新获取的token值
         /*   wx.setStorageSync('token');  */
           //console.log(header);
        }else{
          //其他错误
          //reject('运行出错,请稍后再试');
          //console.log(res.data.msg);
          wx.showToast({//弹出框
            title: '出错了，请重试',
            icon:'error',
            duration:2000
          });
        }
      },
      fail(err){
        //请求失败
        reject(err);
      }
    })
  })
}

//接口可以集合到一块，集中管理
const API = {
 /*  register: (data) => request(POST, `/index.php/index/index/register`,data), //注册
    getLogin:(data)=>request(POST,'/index.php/index/index/login',data),   //登录
    getstrcode:()=>request(GET, `/index.php/index/index/getcode`)    //验证码 */
    userLogin:(data) => request(POST,'/login',data),
    /* 获取用户信息 */
     userInfo:() => request(GET,'/getInfo'),
     /* 查询文件 */
     selectFiles:(data) => request(GET,'/commonModule/fileModule/list',data),
     /* 查询list内容 */
     selectContentList:(data) => request(GET,"/commonModule/contentModule/list",data),
     /* 查询文章内容Byid */
     selectContentById:(id) => request(GET,"/commonModule/contentModule/" + id),
     /* 民宿管理 */
     getHomestayList:(data) => request(GET,"/host/store/list",data),
     /* 民宿查询 */
     getHomestayById:(id) => request(GET,"/host/store/"+ id),
     /* 喜欢收藏查询 */
     getSelfInterestList:(data) => request(GET,"/host/selfInterest/list",data),
     /* 喜欢收藏新增 */
     addSelfInterestList:(data) => request(POST,"/host/selfInterest",data),
     /* 喜欢收藏删除 */
     deleteSelfInterestList:(id) => request(DELETE,"/host/selfInterest/deleteOne/"+id)

  };
  module.exports = {//导出API接口
    API: API,
    baseURL
  }
  /*在需要使用接口的地方引入  const $api= require('../../utils/api').API*/